package com.iot.protocol.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class UdpClientManager {
    private static final Logger logger = LoggerFactory.getLogger(UdpClientManager.class);
    
    private final String serverHost;
    private final int serverPort;
    private final int numClients;
    private final int sendInterval;
    private final List<UdpClient> clients;
    private final ExecutorService executorService;

    public UdpClientManager(String serverHost, int serverPort, int numClients, int sendInterval) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
        this.numClients = numClients;
        this.sendInterval = sendInterval;
        this.clients = new ArrayList<>();
        this.executorService = Executors.newFixedThreadPool(numClients);
    }

    public void start() {
        logger.info("Starting {} UDP clients...", numClients);
        for (int i = 0; i < numClients; i++) {
            UdpClient client = new UdpClient(i + 1, serverHost, serverPort, sendInterval);
            clients.add(client);
            executorService.submit(client);
        }
    }

    public void stop() {
        logger.info("Stopping all clients...");
        clients.forEach(UdpClient::stop);
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        // 配置参数
        String serverHost = "localhost";  // 服务器地址
        int serverPort = 8888;           // 服务器端口
        int numClients = 5;              // 客户端数量
        int sendInterval = 1000;         // 发送间隔（毫秒）

        UdpClientManager manager = new UdpClientManager(serverHost, serverPort, numClients, sendInterval);
        
        // 添加关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(manager::stop));

        try {
            manager.start();
            // 保持主线程运行
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            logger.error("Main thread interrupted", e);
            manager.stop();
        }
    }
} 